<?php

namespace app\xf\controller;

use app\xf\model\QuyuModel;
use app\xf\model\RoleModel;
use app\xf\model\UserModel;
use think\Controller;
use think\Error;
use think\Request;

class QuyuController extends BaseAdminController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        $qyus = QuyuModel::select();
        return $this->SuccessReturn('ok', $qyus);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
        $data = $request->post();

        $name = array_key_exists('name', $data) ? $data['name'] : '';
        $fid = array_key_exists('fid', $data) ? $data['fid'] : 0;
        $contact = array_key_exists('contact', $data) ? $data['contact'] : '';
        $contact_number = array_key_exists('contactNum', $data) ? $data['contactNum'] : '';
        $config = array_key_exists('config', $data) ? $data['config'] : [];


        if ($name == '') return $this->ErrorReturn(403, '缺少必要参数');
        //检查是否存在相同的名称
        if ($fid == 0) {
            $res = QuyuModel::where('name', $name)->where("length(fid) <= 3")->find();
            $fid = $this->setFid($fid);
        } else {

            $a = str_split($fid);
            $res = QuyuModel::where('fid', 'like', "$fid%")
                ->where("length(fid) = " . count($a) + 3)
                ->where("name", $name)
                ->find();

            if ($res) return $this->ErrorReturn(400, '存在相同名称的组织');
            $fid = self::setFid($fid);
        }
        //添加目录
        $quyu = new QuyuModel();
        $quyu->name = $name;
        $quyu->fid = $fid;

      
        if ($contact != '') $quyu->contact = $contact;
        if ($contact_number != '') $quyu->contact_number = $contact_number;
        if ($config != '') $quyu->config = $config;

        $r = $quyu->save();
        if ($r) return $this->SuccessReturn('添加成功', $quyu);
        return $this->ErrorReturn(500, '添加失败，请重新添加');
    }


    //获取fid 生成新的fid
    public function setFid($fid)
    {

        if ($fid == 0) {
            //根目录  获取最后一个fid
            $fids = QuyuModel::where("length(fid) <= 3")
                ->order('id', 'desc')
                ->limit(1)
                ->find();
            $fid = '';
        } else {
            $len = strlen($fid) + 3;
            $fids = QuyuModel::where('fid', 'like', "$fid%")
                ->where("length(fid) <= $len")
                ->where("length(fid) > ($len-3)")
                ->order('id', 'desc')
                ->limit(1)
                ->find();

        }

        if ($fids) {
            //分解fid 创建新的fid
            $chrarr = str_split($fids->fid);

            //先判断最后一位数
            $zlen = ord($chrarr[count($chrarr) - 1]);
            $ylen = ord($chrarr[count($chrarr) - 2]);
            $xlen = ord($chrarr[count($chrarr) - 3]);

            $xval = chr($xlen);
            $yval = chr($ylen);
            $zval = chr($zlen);
//            数字0-9: 48-57
//     小写字母a-z：97-122
            //判断Z值
            if ($zlen == 57 || $zlen == 122) {
                if ($zlen == 57) $zval = 97;
                if ($zlen == 122) $zval = 48;
                //判断Y值
                if ($ylen == 57 || $ylen == 122) {
                    if ($ylen == 57) $yval = 97;
                    if ($ylen == 122) $yval = 48;
                    if ($zlen == 122) {
                        if ($zlen == 57) $yval = 97;
                        if ($zlen == 122) $yval = 48;
                        return "清除数据库中的数据 已满";
                    }
                } else {
                    //Y加一
                    $yval = chr($ylen + 1);
                }
            } else {
                //加一
                $zval = chr($zlen + 1);;
            }
            $newfid = $fid . $xval . $yval . $zval;
        } else {
            //直接新增
            $newfid = $fid . "001";
        }

        return $newfid;
//            return "aa";

    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
        $data = $request->post();
        $id = array_key_exists('id', $data) ? $data['id'] : '';
        $name = array_key_exists('name', $data) ? $data['name'] : '';
        $fid = array_key_exists('fid', $data) ? $data['fid'] : '';
        $contact = array_key_exists('contact', $data) ? $data['contact'] : '';
        $contact_number = array_key_exists('contact_number', $data) ? $data['contact_number'] : '';
        $config = array_key_exists('config', $data) ? $data['config'] : '';

        if ($id == '') return $this->ErrorReturn(403, '缺少必要的参数');
        //获取区域数据
        $quyu = QuyuModel::find($id);
        if (!$quyu) return $this->ErrorReturn(400, '没找到对应的区域数据');
        if ($name != '') {
            //查询是否相同
            if ($fid != '') {
                $a = $fid;
                $a = str_split($a);
                $res = QuyuModel::where('fid', 'like', "$fid%")
                    ->where("length(fid) = " . count($a) + 3)
                    ->where("name", $name)
                    ->find();

                if ($res) {
                    if ($res->id != $id) {
                        return $this->ErrorReturn(400, '存在相同的区域名称数据 请重新填写');
                    }
                }
                substr($a, 0, strlen($a) - 3);
                $tmp_fid = '';
                foreach ($a as $v) {
                    $tmp_fid .= $v;
                }
                if ($tmp_fid != $fid) {

                    $fid2 = self::setFid($fid);
                    $quyu->fid = $fid2;

                }


            } else {

                $res = QuyuModel::where('name', $name)->find();
                if ($res && $res->id != $id) return $this->ErrorReturn(400, '存在相同的区域名称数据 请重新填写');
            }
            $quyu->name = $name;
        }

        if ($contact != '') $quyu->contact = $contact;
        if ($contact_number != '') $quyu->contact_number = $contact_number;
        if ($config != '') $quyu->config = $config;

        $res = $quyu->save();
        return $this->SuccessReturn('修改成功', $quyu);
        return $this->ErrorReturn(500, '修改失败');
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id, Request $request)
    {
        //
        $id = $request->post('id');
        if ($id == 0) return $this->ErrorReturn(400, '区域级别id无效');
        //查询是否存在此区域
        $quyu = QuyuModel::where('id', $id)->find();
        if (!$quyu) return $this->ErrorReturn(404, '找不到此区域');
        //查询区域下是否存在用户
        $user = UserModel::where('qyid', $quyu->id)->find();
        if ($user) return $this->ErrorReturn(400, '此区域下存在用户 请先处理');
        $quyu->delete();
        return $this->SuccessReturn('删除成功');
    }
}
